# -*- coding: utf-8 -*-

from SocketServer import ThreadingMixIn
from SimpleXMLRPCServer import SimpleXMLRPCServer, SimpleXMLRPCRequestHandler

from common import log_msg

class ThreadedXMLRPCServer(ThreadingMixIn, SimpleXMLRPCServer):
	""" Simply make it threaded """
	pass

class RequestHandler(SimpleXMLRPCRequestHandler):
	def address_string(self):
		""" Doing name lookup is sloooooow! """
		host, port = self.client_address[:2]
		return host

	def _dispatch(self, method, params):
		""" We're subclassing SimpleXMLRPCRequestHandler to have 
		a way to pass client IP address to handler function while
		server is running in threaded mode """

		# Registered functions are all stored here
		function = self.server.funcs[method]

		# This function is used as a wrapper function
		# that passes client IP address to "fake" XMLRPC method handler
		# and returns a really used one

		def decor(function, ip_addr):
			def new_function(*args):
				# Just a pretty way of handling exceptions inside 
				# XMLRPC method handlers
				try:
					return function(ip_addr, *args)
				except Exception, err:
					log_msg('Exception occured in XMLRPC thread inside %s() (%s)!' % (method, err))

			return new_function

		return decor(function, self.client_address[0])(*params)


